<template>
  <div v-if="visible" class="settings-modal-overlay" @click.self="$emit('close')">
    <div class="settings-modal">
      <div class="modal-header">
        <span class="modal-title">设置</span>
        <button class="close-btn" @click="$emit('close')">×</button>
      </div>
      <div class="settings-grid">
        <button class="settings-item" @click="handleLogout">
          <span class="item-icon">🔙</span>
          <span class="item-text">返回登录</span>
        </button>
        <button class="settings-item" @click="openCdk">
          <span class="item-icon">🎟️</span>
          <span class="item-text">CDK兑换</span>
        </button>
        <button class="settings-item" @click="goFeedback">
          <span class="item-icon">🐞</span>
          <span class="item-text">Bug反馈</span>
        </button>
        <button class="settings-item" @click="toggleMusic">
          <span class="item-icon">{{ musicEnabled ? '🎵' : '🔇' }}</span>
          <span class="item-text">音乐{{ musicEnabled ? '开启' : '关闭' }}</span>
        </button>
      </div>
      <div class="cdk-form" v-if="showCdkInput">
        <input type="text" v-model="cdkCode" placeholder="输入CDK兑换码" class="cdk-input" />
        <button class="cdk-submit" :disabled="redeemLoading" @click="submitCdk">
          {{ redeemLoading ? '兑换中...' : '兑换' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { redeemCdk } from '@/api/system.js'

export default {
  name: 'SettingsModal',
  props: {
    visible: { type: Boolean, default: false }
  },
  data() {
    return {
      showCdkInput: false,
      cdkCode: '',
      redeemLoading: false,
      musicEnabled: this.getInitMusic()
    }
  },
  methods: {
    getInitMusic() {
      try {
        const val = (typeof uni !== 'undefined') ? uni.getStorageSync('musicEnabled') : localStorage.getItem('musicEnabled')
        return val === null ? true : val === 'true' || val === true
      } catch (e) { return true }
    },
    handleLogout() {
      try {
        if (typeof uni !== 'undefined') {
          uni.removeStorageSync('yid')
          uni.removeStorageSync('userId')
          uni.removeStorageSync('role_id')
        } else {
          localStorage.removeItem('yid')
          localStorage.removeItem('userId')
          localStorage.removeItem('role_id')
        }
      } catch (e) {}
      window.location.hash = '/pages/login/index'
    },
    openCdk() { this.showCdkInput = true },
    async submitCdk() {
      if (!this.cdkCode || this.cdkCode.trim().length < 4) {
        alert('请输入有效的CDK兑换码')
        return
      }
      this.redeemLoading = true
      try {
        const res = await redeemCdk(this.cdkCode.trim())
        if (res && (res.code === 1 || res.success)) {
          alert('兑换成功，奖励已发放')
          this.$emit('close')
          this.showCdkInput = false
          this.cdkCode = ''
        } else {
          alert(res?.message || '兑换失败，请稍后再试')
        }
      } catch (e) {
        console.error('CDK兑换失败', e)
        alert('兑换失败，请检查网络或稍后再试')
      } finally {
        this.redeemLoading = false
      }
    },
    goFeedback() {
      this.$emit('close')
      window.location.hash = '/pages/feedback/index'
    },
    toggleMusic() {
      this.musicEnabled = !this.musicEnabled
      try {
        if (typeof uni !== 'undefined') {
          uni.setStorageSync('musicEnabled', this.musicEnabled)
        } else {
          localStorage.setItem('musicEnabled', String(this.musicEnabled))
        }
      } catch (e) {}
      const bgm = document.getElementById('bgm')
      if (bgm) {
        try { this.musicEnabled ? bgm.play() : bgm.pause() } catch (err) { console.warn('BGM控制失败:', err) }
      }
    }
  }
}
</script>

<style scoped>
.settings-modal-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3000;
}

.settings-modal {
  width: 90%;
  max-width: 420px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.25);
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title { font-weight: bold; }
.close-btn {
  background: transparent;
  border: none;
  font-size: 20px;
  cursor: pointer;
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 16px;
}
.settings-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px;
  border: none;
  border-radius: 8px;
  background: #f7f9fc;
  cursor: pointer;
}
.item-icon { font-size: 18px; }
.item-text { margin-top: 6px; font-size: 14px; }

.cdk-form { padding: 0 16px 16px; }
.cdk-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
}
.cdk-submit {
  margin-top: 10px;
  width: 100%;
  padding: 10px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
}
</style>